from flask import current_app,session

from info import redis_store, db
from info.libs.yuntongxun.sms import CCP
from info.models import User
from info.utils.captcha.captcha import captcha
from info.utils.response_code import RET
from . import passport_blue
from flask import request,make_response,jsonify
from datetime import datetime
import json
import re
import random

@passport_blue.route('/logout',methods=['POST'])
def logout():
    #清楚session的值
    session.pop("user_id",None)
    session.pop("nick_name",None)
    #返回状态        errno是什么意思？
    return jsonify(errno=RET.OK,errmsg="退出成功")
    pass





@passport_blue.route('/login',methods=['POST'])
def login():
    # 1.获取参数
    mobile = request.json.get('mobile')
    password = request.json.get("password")
    # 2.椒盐参数
    #2.1手机号校验
    try:
        user=User.query.filter(User.mobile==mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return  jsonify(errno = RET.DBERR,errmsg = "查询用户失败")
        #上面两句搞不懂是什么意思
    # 2.2密码校验
    if not user.check_passowrd(password):
        return jsonify(errno = RET.DATAERR,errmsg = "密码错误")
        #上面的也看不懂
    # 3.状态保持
    session["user_id"] = user.id
    session["nick_name"] = user.nick_name
    #3.1记录最后的登陆时间
    # try:
    #     user.last_login = datetime.now()
    #     db.session.commit()
    # except Exception as e:
    #     current_app.logger.error(e)
    user.last_login = datetime.now()

    # 4,返回响应
    return jsonify(errno=RET.OK,errmsg="登陆成功")




# 注册用户
# 请求路径: /passport/register
# 请求方式: POST
# 请求参数: mobile, sms_code,password
# 返回值: errno, errmsg
@passport_blue.route('/register', methods=['POST'])
def register():
    #1, 获取参数
    # json_data = request.data
    # dict_data = json.loads(json_data)

    dict_data = request.json #或者是 dict_data = request.get_json()
    mobile = dict_data.get("mobile")
    # sms_code = dict_data.get("sms_code")
    password = dict_data.get("password")

    #2,校验参数
    #2.1 判断用户是否存在
    count = User.query.filter(User.mobile==mobile).count()

    if count > 0:
        return jsonify(errno=RET.DATAERR,errmsg="用户已存在")

    #2.2 短信验证码正确性
    # redis_sms_code = redis_store.get("sms_code:%s"%mobile)
    #
    # if not redis_sms_code:
    #     return jsonify(errno=RET.DATAERR,errmsg="短信验证码过期")
    #
    # if sms_code != redis_sms_code:
    #     return jsonify(errno=RET.DATAERR,errmsg="短信验证码填写错误")

    #3,创建用户对象,入库
    try:
        user = User()
        user.nick_name = mobile
        user.password = password
        user.mobile = mobile

        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="注册失败")

    #4,返回响
    return jsonify(errno=RET.OK,errmsg="注册成功")


# 获取短信验证码
# 请求路径: /passport/sms_code
# 请求方式: POST
# 请求参数: mobile, image_code,image_code_id
# 返回值: errno, errmsg
# @passport_blue.route('/sms_code', methods=['POST'])
# def sms_code():
#     # 1, 获取参数
#     json_data = request.data
#     dict_data = json.loads(json_data)
#     mobile = dict_data.get("mobile")
#     image_code = dict_data.get("image_code")
#     image_code_id = dict_data.get("image_code_id")
#
#     # 2,校验参数
#     # 2.1 校验是否有空值
#     if not all([mobile,image_code,image_code_id]):
#         return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
#
#     # 2.2 手机格式
#     if not re.match(r'1[3-9]\d{9}',mobile):
#         return jsonify(errno=RET.PARAMERR,errmsg="手机号格式有误")
#
#     # 2.3 图片验证码正确性
#     redis_image_code = redis_store.get("image_code:%s"%image_code_id)
#     if not redis_image_code:
#         return jsonify(errno=RET.PARAMERR,errmsg="图片验证码过期")
#
#     redis_store.delete("image_code:%s" % image_code_id)
#
#     if image_code.lower() != redis_image_code.lower():
#         return jsonify(errno=RET.DATAERR,errmsg="图片验证码填写错误")
#
#     # 3,发送短信,数据入库
#     sms_code = "%06d"%random.randint(0,999999)
#     current_app.logger.debug("sms_code = %s"%sms_code)
#     # ccp = CCP()
#     # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
#     #
#     # if result == -1:
#     #     return jsonify(errno=RET.THIRDERR,errmsg="发送失败")
#
#     redis_store.set("sms_code:%s"%mobile,sms_code,300)
#
#     # 4,返回响应
#     return jsonify(errno=RET.OK,errmsg="发送成功")


# 请求路径: /passport/image_code
# 请求方式: GET
# 请求参数: cur_id, pre_id
# 返回值: 图片验证码
@passport_blue.route('/image_code')
def image_code():
    # - 1, 获取参数,cur_id
    cur_id =  request.args.get("cur_id")
    pre_id =  request.args.get("pre_id")

    # - 2,校验校验参数
    if not cur_id:
        return "参数不全"

    # 2,1 判断上一个图片验证码编号是否存在,存在则删除
    if pre_id:
        redis_store.delete("image_code:%s" % pre_id)

    # - 3,生成图片验证码
    name, text, image_code = captcha.generate_captcha()

    # - 4,存储到redis中
    redis_store.set("image_code:%s"%cur_id,text,300)

    # - 5,返回图片验证码
    response = make_response(image_code)
    response.headers["Content-Type"] = "image/png"
    return response
